<?php

require_once('functions.php');
$member_id	= $session->get("member_id");
$gametype	= GAME1;

// Update top players.
$template->assign("players",get_top_players($gametype));

// Check member is logged in.
check_login($member_id);

// Check if our system is no inputed questions.
check_no_questions($gametype, MAX_QUESTION_GAME1);

// Check if logged member is finished this game.
check_finish_game($member_id, $gametype);

$act = isset($_REQUEST['act']) ? $_REQUEST['act'] : -2;

// Default response.
$response = array(
	"back"			=> _LB_REDO,
	"back_link"		=> "getthepicture.php?act=" . BACK,
	"forward"		=> _LB_NEXT,
	"forward_link"	=> "getthepicture.php?act=" . FORWARD,
	"title"			=> "Beauty of highland",
	"image"			=> "1_1.jpg",
	"score"			=> 0,
	"remaining"		=> 19,
	"is_last"		=> 0,
	"answer"		=> array(),
);

// Get randomize question to array
$arr_questions = get_random_questions($gametype, $member_id, MAX_QUESTION_GAME1);
//---------------------------------

// Array answers
$current_game = $session->get('current_game') ? $session->get('current_game') : GAME1;
if($current_game != GAME1)
{
	$session->set('current',1);
	$session->set('current_game',GAME1);
}
else
{
	$current = $session->get('current') ? $session->get('current') : 1;
}

switch (intval($act)) {
	case START:
		$session->set('current',$current);
		$response["back"] = "";
		$response["back_link"] = "javascript:void(0);";
		break;
	case BACK:
		$current--;
		if($current <= MIN_QUESTION) // first question
		{
			$current = MIN_QUESTION;
			$response["back"] = "";
			$response["back_link"] = "javascript:void(0);";
		}
		$session->set('current',$current);
		break;
	case FORWARD:
		$current++;
		if($current >= MAX_QUESTION_GAME1) // last question
		{
			$current = MAX_QUESTION_GAME1;
			$response["is_last"] = 1;
			$response["forward"] = _LB_FINISH;
			$response["forward_link"] = "getthepicture.php?act=" . END;
		}
		$session->set('current',$current);
		break;
	case END:
		// Calculate and save scores.
		$query_insert_result = "INSERT INTO results(id, member_id, question_type_id, total, answered, passed, date_done)
			SELECT
			  NULL                      AS id,
			  member_answer_question.member_id,
			  question.question_type_id,
			  ".MAX_QUESTION_GAME1."          AS total,
			  IFNULL(COUNT(member_answer_question.question_id),0) AS answered,
			  IFNULL(SUM(answer.is_correct),0) AS passed,
			  NOW()                     AS date_done
			FROM member_answer_question
			  INNER JOIN question
				ON question.id = member_answer_question.question_id
			  INNER JOIN answer
				ON answer.id = member_answer_question.answer_id
			WHERE question.question_type_id = $gametype
				AND member_answer_question.member_id = {$member_id}
			GROUP BY member_id, question_type_id
			ON DUPLICATE KEY UPDATE passed = VALUES(passed)
			";
		$database->query($query_insert_result);
		if($database->get_success_rows() == 0)
		{
			$query_insert_result = "INSERT INTO results(id, member_id, question_type_id, total, answered, passed, date_done)
									VALUES ('%s','%d','%d','%d','%d','%d',NOW())";
			$query_insert_result = sprintf($query_insert_result, 'NULL', $member_id, $gametype, MAX_QUESTION_GAME1, 0, 0);
			$database->query($query_insert_result);
		}
		$database->set_query("SELECT total, answered, passed FROM results WHERE member_id = $member_id");
		$result = $database->get_assoc();
		$response["result"] = $result;
		$session->set("member_score_game".$gametype, $result['passed']);
		$response["back"] = "";
		$response["forward"] = "";
		$response["end"]	 = 1;
		$response["title"] = _LB_CONGRATULATIONS;
		$response["message"] = _MSG_CONGRATULATIONS_INFO;
		$response['players'] = get_top_players($gametype);
		echo json_encode($response);die();
		break;
	case ANSWER:
		$answer_index = isset($_REQUEST['index']) ? $_REQUEST['index'] : 0;
		if($answer_index > 0 && $answer_index <= 4)
		{
			$question_id	= $arr_questions[$current]['id'];
			$answer_id		= $arr_questions[$current]['answers'][$answer_index]['id'];
			$database->set_query("SELECT COUNT(question_id) FROM member_answer_question WHERE question_id = $question_id AND member_id = $member_id");
			$exist = $database->get_result();
			if($exist)
			{
				$database->query("UPDATE member_answer_question SET answer_id = $answer_id WHERE question_id = $question_id AND member_id = $member_id");
			}
			else
			{
				$database->query("INSERT INTO member_answer_question (question_id, member_id, answer_id) VALUES ($question_id, $member_id, $answer_id)");
			}
			// Reset selected answer.
			$arr_questions[$current]['answers'][1]['selected'] = '';
			$arr_questions[$current]['answers'][2]['selected'] = '';
			$arr_questions[$current]['answers'][3]['selected'] = '';
			$arr_questions[$current]['answers'][4]['selected'] = '';
			
			$arr_questions[$current]['answers'][$answer_index]['selected'] = 'selected';
			$session->set('arr_question_' . $gametype, $arr_questions);
			if($current >= MAX_QUESTION_GAME1) // last question
			{
				$response["is_last"] = 1;
				$response["forward"] = _LB_FINISH;
				$response["forward_link"] = "getthepicture.php?act=" . END;
			}
		}
		break;
	case TOP_PLAYER:
		$top_members = get_top_players($gametype);
		echo json_encode($top_members);die();
		break;
	default: 				
		$response["back"] = "";
		$response["forward"] = "";
		break;
}

if(!empty($response['back']) || !empty($response['forward']))
{
	// Get remaining questions
	$response["remaining"] = get_remaining_question($member_id, $gametype, MAX_QUESTION_GAME1);
	//-------------------------
	
	// Get question info.
	$response['question'] = $arr_questions[$current];
	//-------------------------
	
	// Cached current question number.
	$session->set('current', $current);
	
	// Ajax response.
	echo json_encode($response);die();
}

$template->display("getthepicture.tpl");
?>
